<?php

namespace App\Models\Api;

use Illuminate\Database\Eloquent\Model;

class ApiModel extends Model
{
    protected $guarded = [];

    /** 取主表中(子表不存在)的数据,类似于left join去除inner join后剩下的部分,@todo 可以改成「whereDoesntHave」方法
     * 例子:企业查看简历浏览记录表中,不是黑名单的简历,http://www.cnblogs.com/jameshappy/p/6038706.html
     * 该方法的执行的结果是添加了一个where((select count(1) as count from 子表 where ? = ?...)<=0)
     * @param $left_query
     * @param $right (子表的model文件名,namespace默认是BasicModel.php的namespace)
     * @param $closure (两个参数,第一个是子表的$query,第二个参数是主表名,闭包里是写inner join的where条件)
     */
    public function scopeLeftNotInRight($left_query, $right, $closure)
    {
        //表前缀
        $prefix = config('database.connections.' . config('database.default') . '.prefix');
        //主表名
        $LeftTable = "`$prefix$this->table`";
        //子表实例
        $instance = new $right;

        //新建子表$query
        $right_query = $instance->newQuery();

        //执行闭包函数,往$right_query传入查询条件,分别是$right_query,$LeftTable
        $closure($right_query, $LeftTable);

        $right_query->select(\DB::raw('count(1) as count'));

        //拿到完整的sql语句
        $total = $right_query->toSql();
        //所有where值
        $wheres = $right_query->getQuery()->wheres;

        //用值替换掉sql语句中的?
        foreach ($wheres as $where) {
            $total = str_replace_first('?', $where['value'], $total);
        }

        //给主表添加上条件 sql例子:
        //主表 where ((select count(1) as count from `子表` where `personal_uid` = 主表.personal_uid)<=0)
        $left_query->whereRaw("(($total)<=0)");
    }
}